import cv2 as cv
import copy
import matplotlib.pyplot as plt
import numpy as np

img=cv.imread('G:\\Learn\\CSDN\\Work\\mili.gif')
source= cv.cvtColor(img,cv.COLOR_RGB2GRAY)
th1,src= cv.threshold(source,0,255,cv.THRESH_OTSU)
print(th1)
#形态学处理，去除噪声
element=cv.getStructuringElement(cv.MORPH_CROSS,(3,3))
src =cv.morphologyEx(src,cv.MORPH_CLOSE,element)

#以下是图像分割
seg= copy.copy(src)
contours, hierarchy = cv.findContours(seg,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)

#以下是进行筛选
length=len(contours)
count=0
for i in range(0,length):
    area=cv.contourArea(contours[i])
    if(area<10):  #滤除面积小于10的分割结果：可能是噪声
        continue
    count+=1   #统计米粒个数
    print("blob {0}:{1}".format(i,area))

    x,y,w,h=cv.boundingRect(contours[i])  #外接矩形
    cv.rectangle(img,(x,y),(x+w,y+h),(0,0,255),1)

    cv.putText(img,str(count),(x,y),cv.FONT_HERSHEY_PLAIN,0.5,(0,255,0),1)
print('米粒数量:',count)

plt.hist(img.ravel(),256)
plt.show()
titles=['Source Image','Blur Image']
images=[img,src]
for i in range(2):
    plt.subplot(1, 2, i + 1), plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([]), plt.yticks([])
plt.show()

cv.waitKey(0)
cv.destroyAllWindows()

